package com.rgs.gateway.web.common.design.sign.strategy;

import com.rgs.gateway.common.enums.SignTypeEnum;
import com.rgs.gateway.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Map;

/**
 * @author RenGaoshuai
 * @date 2024/7/1 16:45
 * @description
 */
@Slf4j
public class SimuAiGatewaySignStrategy implements GatewaySignStrategy {
    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    @Override
    public String getSign(String appKey, String appSecret, String timestamp, Map<String, Object> params) {
        //转换字符串位base64
        String appidBaer = encode(appKey);
        //拼接字符串
        StringBuilder stringbu = new StringBuilder();
        stringbu.append(appidBaer);
        stringbu.append(appSecret);
        stringbu.append(timestamp);
        try {
            //转化位MD5
            String md5 = DigestUtils.md5DigestAsHex(stringbu.toString().getBytes()).toUpperCase();
            return md5;
        } catch (Exception e) {
            log.error("易私慕验签生成数据异常,异常信息为：{}",e.getMessage());
            throw new ServiceException("易私慕验签生成数据异常");
        }
    }

    @Override
    public Integer getSignType() {
        return SignTypeEnum.SIMUAI.getCodeValue();
    }

    /**
     * 将加密后的字符串进行解密
     * @param encodedText
     * @return
     */

    public static String decode(String encodedText) {
        String text = null;
        try {
            text = new String(decoder.decode(encodedText), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return text;
    }

    public static String encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = encoder.encodeToString(textByte);
        return encodedText;
    }
}
